#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QSqlDatabase>
#include <QDebug>
#include <QMessageBox>
#include <QSqlQuery>
#include <QSqlError>
#include <QSqlQueryModel>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    qDebug() << QSqlDatabase::drivers();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::connectDB()
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", "myConnection");
    db.setDatabaseName("mydb");
    bool r = db.open();
    if(r == true){
        QMessageBox::information(0, "通知", "恭喜，数据库连接成功");
    }else{
        QMessageBox::critical(0, "警告", "注意，数据库连接失败");
    }
}

void MainWindow::createTable()
{
    QSqlDatabase db = QSqlDatabase::database("myConnection");
    QSqlQuery sqlQuery(db);
    bool r = sqlQuery.exec("create table student(id integer, name verchar, score integer)");
    qDebug() << r;

}

void MainWindow::insertRecord()
{
    int id = ui->lineEdit_id->text().toInt();
    QString name = ui->lineEdit_name->text();
    int score = ui->lineEdit_score->text().toInt();
    QSqlDatabase db = QSqlDatabase::database("myConnection");
    QSqlQuery sqlQuery(db);
    bool r = sqlQuery.exec(QString("insert into student values(%1, '%2', %3)").arg(id).arg(name).arg(score));
    if(r == true){
        qDebug() << "插入成功";
    }else{
        sqlQuery.lastError().text();
    }

}

void MainWindow::queryAll()
{
    QSqlDatabase db = QSqlDatabase::database("myConnection");
    QSqlQuery sqlQuery(db);
    bool r = sqlQuery.exec("select * from student");
    while(sqlQuery.next()){
        qDebug() << sqlQuery.value("id").toInt() << sqlQuery.value("name").toString() << sqlQuery.value("score").toInt();
    }

}

void MainWindow::queryModel()
{
    QSqlDatabase db = QSqlDatabase::database("myConnection");
    QSqlQueryModel* queryModel = new QSqlQueryModel(this);
    queryModel->setQuery("select * from student", db);
    ui->tableView->setModel(queryModel);
    qDebug() << queryModel->lastError().text();
}

void MainWindow::on_pushButton_clicked()
{
    connectDB();
}

void MainWindow::on_pushButton_2_clicked()
{
    createTable();
}

void MainWindow::on_pushButton_3_clicked()
{
    insertRecord();
}

void MainWindow::on_pushButton_4_clicked()
{
    queryAll();
}

void MainWindow::on_pushButton_5_clicked()
{
   queryModel();
}
